package com.example.pingze.controller;

import com.example.pingze.entity.MyInfo;
import com.example.pingze.entity.UserLogin;
import com.example.pingze.exception.PingZeException;
import com.example.pingze.service.LoginService;
import com.example.pingze.service.MyInfoService;
import com.example.pingze.utils.ResultVOUtils;
import com.example.pingze.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

@RestController
@RequestMapping("/myInfo")
@CrossOrigin(origins = "*")
public class MyInfoController {
    @Autowired
    private MyInfoService myInfoService;
    @Autowired
    private LoginService loginService;

    //修改用户信息
    @PostMapping("/update")
    public Result<MyInfo> update(@RequestBody MyInfo myInfo){
        if(StringUtils.isEmpty(myInfo.getAccount())){
            throw new PingZeException("账号不能为空");
        }
        int len = myInfo.getNickname().length();
        if (len > 10){
            return ResultVOUtils.error("用户名字太长啦!");
        }
        MyInfo info = myInfoService.update(myInfo);
        return ResultVOUtils.result(info);
    }
    @PostMapping("/getMyInfo")
    public Result<MyInfo> getMyInfo(@RequestBody MyInfo myInfo){
        String account = myInfo.getAccount();
        if(account == null){
            throw new PingZeException("账号为空");
        }else{
            MyInfo info = myInfoService.findMyInfoByAccount(account);
            return ResultVOUtils.result(info);
        }
    }


    /**
     * 通过account修改头像
     * 先将头像解码
     * 再下载到本地
     * 将本地路径存储到数据库
     *
     * @param myInfo
     * @return
     */
    @PostMapping("/updateAvatar")
    public Result<MyInfo> updateAvatar(@RequestBody MyInfo myInfo) throws IOException {

        String avatar = myInfo.getAvatar();
        String account = myInfo.getAccount();
        if(account == null){
            throw new PingZeException("用户账号为空");
        }
        if(avatar == null){
            throw new PingZeException("头像信息为空");
        }
        MyInfo myInfoByAccount = myInfoService.findMyInfoByAccount(myInfo.getAccount());
        if(myInfoByAccount != null){
            //将图片进行解码
            byte[] avatarBytes = Base64.getMimeDecoder().decode(avatar);
            //将图片存到本地
            String filePath = "D:\\myInfo\\avatar\\" + account + ".jpg";
            File avatarFile = new File(filePath);
            OutputStream stream = new BufferedOutputStream(new FileOutputStream(avatarFile));
            stream.write(avatarBytes);
            //将本地路径存入数据库中
            myInfoByAccount.setAvatar(filePath);
            stream.flush();
            stream.close();
        }
        MyInfo update = myInfoService.updateAvatar(myInfoByAccount);
        return ResultVOUtils.result(update);
    }

    @PostMapping("/getAvatar")
    public Result<String> getAvatar(@RequestBody MyInfo myInfo) throws IOException {
        if(myInfo.getAccount() == null) {
            throw new PingZeException("用户账号为空");
        }
        //从数据库中获取图片路径
        MyInfo myInfoByAccount = myInfoService.findMyInfoByAccount(myInfo.getAccount());
        String avatar = myInfoByAccount.getAvatar();
        //读取本地路径的图片，并将其以Base64的编码格式返回
        Path path = Paths.get(avatar);
        byte[] avatarBytes = Files.readAllBytes(path);
        String avatarData = Base64.getMimeEncoder().encodeToString(avatarBytes);

        return ResultVOUtils.result(avatarData);
    }
    /**
     * 修改背景图片
     */
    @PostMapping("/updateBg")
    public Result<MyInfo> updateBg(@RequestBody MyInfo myInfo) throws IOException {

        String bg = myInfo.getBg();
        String account = myInfo.getAccount();
        if(account == null){
            throw new PingZeException("用户账号为空");
        }
        if(bg == null){
            throw new PingZeException("头像信息为空");
        }
        MyInfo myInfoByAccount = myInfoService.findMyInfoByAccount(myInfo.getAccount());
        if(myInfoByAccount != null){
            //将背景图片进行解码
            byte[] bgBytes = Base64.getMimeDecoder().decode(bg);
            //将背景图片存到本地
            String filePath = "D:\\myInfo\\bg\\" + account + ".jpg";
            File bgFile = new File(filePath);
            OutputStream stream = new BufferedOutputStream(new FileOutputStream(bgFile));
            stream.write(bgBytes);
            //将本地路径存入数据库中
            myInfoByAccount.setBg(filePath);
            stream.flush();
            stream.close();
        }
        MyInfo update = myInfoService.updateBg(myInfoByAccount);
        return ResultVOUtils.result(update);
    }

    @PostMapping("/getBg")
    public Result<String> getBg(@RequestBody MyInfo myInfo) throws IOException {
        if(myInfo.getAccount() == null) {
            throw new PingZeException("用户账号为空");
        }
        //从数据库中获取背景图片路径
        MyInfo myInfoByAccount = myInfoService.findMyInfoByAccount(myInfo.getAccount());
        String bg = myInfoByAccount.getBg();
        //读取本地路径的图片，并将其以Base64的编码格式返回
        Path path = Paths.get(bg);
        byte[] bgBytes = Files.readAllBytes(path);
        String bgData = Base64.getMimeEncoder().encodeToString(bgBytes);

        return ResultVOUtils.result(bgData);
    }



    /**
     * 后台管理系统
     */
    @CrossOrigin
    @PostMapping("/page")
    public Result<Page<MyInfo>> getList(
            MyInfo myInfo,
            @RequestParam(name = "pageCode", required = false, defaultValue = "1") Integer pageCode,
            @RequestParam(name = "pageSize", required = false, defaultValue = "4") Integer pageSize
    ){
        if(pageCode< 1){
            throw new PingZeException("页码不能小于1");
        }
        Sort.Order accountOrder = Sort.Order.asc("account");
        Sort sort = Sort.by(accountOrder);
        Pageable pageable = PageRequest.of(pageCode - 1, pageSize, sort);
        Page page = myInfoService.getMyInfoList(myInfo, pageable);
        return ResultVOUtils.result(page);
    }
    @CrossOrigin
    @PostMapping("/edit")
    //通过账号修改字段
    public Result<MyInfo> edit(String account,String nickname,String sexy,String myTag,String mySign,String birthday,String avatar,String bg){
        if(account == null){
            throw new PingZeException("账号为空");
        }
        MyInfo update1 = myInfoService.edit(account, nickname, sexy, myTag, mySign,birthday,avatar,bg);
        return ResultVOUtils.result(update1);
    }
    @CrossOrigin
    @Transactional
    @PostMapping("/delete")
    public Result<String> delete(String account){
        if(account == null){
            throw new PingZeException("account为空");
        }
        MyInfo info = myInfoService.findMyInfoByAccount(account);
        if(info != null){
            myInfoService.delete(info);
        }
        UserLogin login = loginService.findUserLoginByAccount(account);
        if (login != null){
            loginService.delete(login);
        }
        return ResultVOUtils.success("delete success");
    }
}
